﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebCamera.WebSocket
{
    public class HCCameraInfo
    {
        public string Name { get; set; }
        public string Ip { get; set; }
        public int Port { get; set; }
        public string User { get; set; }
        public string Pass { get; set; }
    }
    public class CameraInfo
    {
        public IntPtr fMP4Handle = IntPtr.Zero;
        public bool fMP4 = false;
        public int UserId = -1;
        public int RealHandle = -1;
        public PsToH264Util PsToH264Util = new PsToH264Util();
        public Thread Thread;
        public AutoResetEvent Exit;
        public System.Net.WebSockets.WebSocket Socket;
        public List<byte[]> Datas = new List<byte[]>();
    }
    public class HCCamera : WebSocketManagerMiddleware.WebSocketHandler
    {
        public static List<HCCameraInfo> Cameras { get; set; }
        private fMP4.fMP4Callback _callback;
        CHCNetSDK.REALDATACALLBACK _realData = null;
        private static bool _bInitSdk;
        private Dictionary<System.Net.WebSockets.WebSocket, CameraInfo> _cameras = new Dictionary<System.Net.WebSockets.WebSocket, CameraInfo>();
        public HCCamera(WebSocketConnectionManager webSocketConnectionManager) : base(webSocketConnectionManager)
        {
            if (_bInitSdk == false)
            {
                _bInitSdk = CHCNetSDK.NET_DVR_Init();
                CHCNetSDK.NET_DVR_SetLogToFile(0, "", true);
                CHCNetSDK.NET_DVR_SetReconnect(5000, 1);
            }
            _realData = RealDataCallBack;
            _callback = MP4CallbackAsync;
        }

        public override Task OnDisconnected(System.Net.WebSockets.WebSocket socket)
        {
            Remove(socket);
            return base.OnDisconnected(socket);
        }

        private void Remove(System.Net.WebSockets.WebSocket socket)
        {
            CameraInfo info = null;
            lock (_cameras)
            {
                _cameras.TryGetValue(socket, out info);
                _cameras.Remove(socket);
            }
            Close(info);
        }

        private void Close(CameraInfo info)
        {
            if (info == null)
                return;
            if (info.RealHandle >= 0)
            {
                CHCNetSDK.NET_DVR_StopRealPlay(info.RealHandle);
                info.RealHandle = -1;
            }
            if (info.UserId >= 0)
            {
                CHCNetSDK.NET_DVR_Logout(info.UserId);
                info.UserId = -1;
            }
            if (info.Thread != null)
            {
                info.Exit.Set();
                info.Thread.Join();
                info.Exit.Close();
                info.Exit = null;
                info.Thread = null;
            }

            if (info.fMP4Handle != IntPtr.Zero)
            {
                fMP4.fMP4_Close(info.fMP4Handle);
                info.fMP4Handle = IntPtr.Zero;
            }
        }

        private async void MP4CallbackAsync(byte[] data, int len, IntPtr userData)
        {
            KeyValuePair<System.Net.WebSockets.WebSocket, CameraInfo> info;
            lock (_cameras)
            {
                info = _cameras.FirstOrDefault(p => p.Value.fMP4Handle == userData);
            }

            if (info.Key != null)
            {
                if (info.Key.State == WebSocketState.Open)
                {
                    try
                    {
                        await info.Key.SendAsync(new ArraySegment<byte>(array: data, 0, len), WebSocketMessageType.Binary, true, CancellationToken.None);
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine(e);
                    }
                }
            }
        }
        private void RealDataCallBack(Int32 lRealHandle, UInt32 dwDataType, IntPtr pBuffer, UInt32 dwBufSize, IntPtr pUser)
        {
#if DEBUG
            var sw = new Stopwatch();
            sw.Start();
#endif
            try
            {
                if (CHCNetSDK.NET_DVR_SYSHEAD == dwDataType)
                    return;

                KeyValuePair<System.Net.WebSockets.WebSocket, CameraInfo> info;
                lock (_cameras)
                {
                    info = _cameras.FirstOrDefault(p => p.Value.RealHandle == lRealHandle);
                }

                if (info.Key != null)
                {
                    byte[] sData = new byte[dwBufSize];
                    Marshal.Copy(pBuffer, sData, 0, (Int32) dwBufSize);

                    lock (info.Value.Datas)
                    {
                        info.Value.Datas.Add(sData);
                    }
                }
            }
            finally
            {
#if DEBUG
                sw.Stop();
                if (sw.ElapsedMilliseconds > 0)
                {
                    Debug.WriteLine($"RealDataCallBack: {sw.ElapsedMilliseconds}");
                }
#endif
            }
        }

        public virtual bool GetCameraInfo(string name, ref string addr, ref int port, ref string user, ref string password, ref int chn)
        {
            if (Cameras == null)
                return false;
            var cam = Cameras.FirstOrDefault(p => p.Name == name);
            if (cam == null)
                return false;

            addr = cam.Ip;
            port = cam.Port;
            user = cam.User;
            password = cam.Pass;
            chn = 0;
            return true;
        }

        private async void OnThread(object par)
        {
            CameraInfo info = (CameraInfo)par;
            List<byte[]> datas = new List<byte[]>();
            while (info.Exit.WaitOne(10) == false)
            {
#if DEBUG
                var sw = new Stopwatch();
                sw.Start();
#endif
                datas.Clear();
                lock (info.Datas)
                {
                    datas.AddRange(info.Datas);
                    info.Datas.Clear();
                }
                if (datas.Count == 0)
                    continue;

                foreach (var d in datas)
                {
                    info.PsToH264Util.Write(d);
                }
                info.PsToH264Util.ExecuteParsing();
                var data = info.PsToH264Util.Read();
                if (data != null && data.Length > 0)
                {
                    if (info.fMP4 && info.fMP4Handle != IntPtr.Zero)
                    {
                        fMP4.fMP4_WriteH264(info.fMP4Handle, data, data.Length);
                    }
                    else
                    {
                        await info.Socket.SendAsync(new ArraySegment<byte>(array: data), WebSocketMessageType.Binary, true, CancellationToken.None);
                    }
                }
#if DEBUG
                sw.Stop();
                if (sw.ElapsedMilliseconds > 0)
                {
                    Debug.WriteLine($"OnThread: {sw.ElapsedMilliseconds}");
                }
#endif
            }
        }

        protected override async void StartCamera(System.Net.WebSockets.WebSocket socket, string channel, string args)
        {
            CameraInfo info;
            lock (_cameras)
            {
                if (!_cameras.TryGetValue(socket, out info))
                {
                    info = new CameraInfo();
                    _cameras.Add(socket, info);
                }
            }

            Close(info);
            info.Socket = socket;
            if (!string.IsNullOrEmpty(args))
            {
                bool bMP4;
                if (bool.TryParse(args, out bMP4))
                {
                    info.fMP4 = true;
                    info.fMP4Handle = fMP4.fMP4_CreateH264();
                    fMP4.fMP4_SetCallback(info.fMP4Handle, _callback, info.fMP4Handle);
                }
            }

            info.Thread = new Thread(OnThread);
            info.Exit = new AutoResetEvent(false);
            info.Thread.Start(info);

            string addr = "", user = "", password = "";
            int port = 8000, chn = 1;
            if (!GetCameraInfo(channel, ref addr, ref port, ref user, ref password, ref chn))
            {
                await socket.SendAsync(Encoding.UTF8.GetBytes("找不到该摄像头配置信息"), WebSocketMessageType.Text, true, CancellationToken.None);
                Remove(socket);
                return;
            }
            var deviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();

            info.UserId = CHCNetSDK.NET_DVR_Login_V30(addr, port, user, password, ref deviceInfo);
            if (info.UserId < 0)
            {
                var err = CHCNetSDK.NET_DVR_GetLastError();
                var str = CHCNetSDK.NET_DVR_GetErrorMsg(ref err);
                Trace.WriteLine($"NET_DVR_Login_V30 failed: {err}, {str}");
                await socket.SendAsync(Encoding.UTF8.GetBytes("登录失败: " + str), WebSocketMessageType.Text, true, CancellationToken.None);
                Remove(socket);
                return;
            }
            
            var lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
            lpPreviewInfo.lChannel = chn;
            lpPreviewInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
            lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
            lpPreviewInfo.bBlocked = false; //0- 非阻塞取流，1- 阻塞取流
            lpPreviewInfo.dwDisplayBufNum = 0; //播放库播放缓冲区最大缓冲帧数
            lpPreviewInfo.byProtoType = 0;
            lpPreviewInfo.byPreviewMode = 0;
            info.RealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(info.UserId, ref lpPreviewInfo, _realData, IntPtr.Zero);
            if (info.RealHandle < 0)
            {
                var err = CHCNetSDK.NET_DVR_GetLastError();
                Trace.WriteLine($"NET_DVR_RealPlay_V40 failed: {err}, {CHCNetSDK.NET_DVR_GetErrorMsg(ref err)}");
                await socket.SendAsync(Encoding.UTF8.GetBytes("播放失败"), WebSocketMessageType.Text, true, CancellationToken.None);
                Remove(socket);
                return;
            }
        }

        protected override void StopCamera(System.Net.WebSockets.WebSocket socket)
        {
            Remove(socket);
        }
    }
}
